<?php
/**
 * Created by PhpStorm.
 * User: xiaosq
 * Date: 2018/6/21
 * Time: 14:18
 */

namespace App\Http\Controllers\Api\Meeting;


use App\Api\ErrCode;
use App\Handlers\Oss;
use App\Http\Controllers\Api\ApiController;
use App\Models\MeetingUser;
use Illuminate\Http\Request;
use Validator;
use Lang;
use App\Handlers\Face;
use App\Api\Exceptions\ApiCommonException;
use App\Models\Meeting;

class PersonsController extends ApiController
{
    /**
     * 图片base64人脸检索
     * @param Request $request
     */
    public function multiFaceIdentifyBase(Request $request, MeetingUser $meetingUser)
    {
        $group_id = (string) $request->group_id;
        $image = $request->image;

        // 创建验证规则
        $rules = [
            'group_id'      => 'required',
            'image'      => 'required',
        ];

        // 自定义验证消息
        $messages = [
            'group_id.required'      => Lang::get('person.group_id').Lang::get('common.required'),
            'image.required'      => Lang::get('person.image').Lang::get('common.required'),
        ];

        //开始验证
        $validator = Validator::make($request->all(), $rules, $messages);

        if($validator->fails())
        {
            throw ApiCommonException::requestParamsErr($validator->messages()->first());
        }

        //会议状态验证
        $meeting_info = Meeting::select('sign_in_start_at', 'sign_in_end_at')->where('id', $group_id)->first();

        if (empty($meeting_info)) {
            throw ApiCommonException::meetingSignInIsEmpty();
        }

        $now = time();
        $sign_in_start_at_str = strtotime($meeting_info->sign_in_start_at);
        $sign_in_end_at_str = strtotime($meeting_info->sign_in_end_at);

        if ($now < $sign_in_start_at_str) {
            throw ApiCommonException::meetingSignInNotBeginning();
        }

        if ($now > $sign_in_end_at_str) {
            throw ApiCommonException::meetingSignInIsFinished();
        }

        $face = new Face();

        $ret = $face->multiFaceIdentifyBase($image, $group_id);

        if ($ret['errorcode'] != 0) {
            throw ApiCommonException::youTuApiErr($ret['errorcode']);
        }

        if (!isset($ret['results'][0]['candidates'][0]) || empty($ret['results'][0]['candidates'][0])) {
            throw ApiCommonException::youTuMultiFaceIdentifyErr();
        }

        $confidence = $ret['results'][0]['candidates'][0]['confidence'];

        if ($confidence <= 80) {
            throw ApiCommonException::youTuFaceVerifyErr();
        }

        $face_id = $ret['results'][0]['candidates'][0]['face_id'];

        $meeting_user_count = $meetingUser->where('meeting_id', '=', $group_id)->where('person_face_id', '=', $face_id)->count();

        if ($meeting_user_count == 0) {
            throw ApiCommonException::faceVerifyErr();
        }

        $meeting_user_count = $meetingUser->where('meeting_id', '=', $group_id)->where('person_face_id', '=', $face_id)->where('status', '=', 2)->count();

        if ($meeting_user_count > 0) {
            $result_data = $this->imageUserInfo($group_id, $face_id, $face);
            return $this->getResponseFail(ErrCode::FACE_VERIFY_REPEAT_SIGN_IN_ERR, Lang::get('person.repeat_sign_in'), $result_data);
        }

        $update_data['status'] = 2;
        $update_data['sign_in_at'] = date('Y-m-d H:i:s');

        $r = $meetingUser->where('meeting_id', '=', $group_id)->where('person_face_id', '=', $face_id)->update($update_data);

        if (!$r) {
            throw ApiCommonException::faceVerifyErr();
        }

        Meeting::where('id', $group_id)->increment('sign_in_num', 1);

        $result_data = $this->imageUserInfo($group_id, $face_id, $face);

        return $this->getResponseSuccess($result_data);
    }

    /**
     * 手机号签到
     * @param Request $request
     * @param MeetingUser $meetingUser
     */
    public function verifyByMobile(Request $request, MeetingUser $meetingUser)
    {
        $group_id = (string) $request->group_id;
        $mobile = $request->mobile;

        // 创建验证规则
        $rules = [
            'group_id'      => 'required',
            'mobile'      => 'required',
        ];

        // 自定义验证消息
        $messages = [
            'group_id.required'      => Lang::get('person.group_id').Lang::get('common.required'),
            'mobile.required'      => Lang::get('person.mobile').Lang::get('common.required'),
        ];

        //开始验证
        $validator = Validator::make($request->all(), $rules, $messages);

        if($validator->fails())
        {
            throw ApiCommonException::requestParamsErr($validator->messages()->first());
        }

        //会议状态验证
        $meeting_info = Meeting::select('sign_in_start_at', 'sign_in_end_at')->where('id', $group_id)->first();

        if (empty($meeting_info)) {
            throw ApiCommonException::meetingSignInIsEmpty();
        }

        $now = time();
        $sign_in_start_at_str = strtotime($meeting_info->sign_in_start_at);
        $sign_in_end_at_str = strtotime($meeting_info->sign_in_end_at);

        if ($now < $sign_in_start_at_str) {
            throw ApiCommonException::meetingSignInNotBeginning();
        }

        if ($now > $sign_in_end_at_str) {
            throw ApiCommonException::meetingSignInIsFinished();
        }

        $meeting_user_count = $meetingUser->where('meeting_id', '=', $group_id)->where('mobile', '=', $mobile)->count();

        if ($meeting_user_count == 0) {
            throw ApiCommonException::faceVerifyErr();
        }

        $meeting_user_count = $meetingUser->where('meeting_id', '=', $group_id)->where('mobile', '=', $mobile)->where('status', '=', 2)->count();

        $face = new Face();

        if ($meeting_user_count > 0) {
            $result_data = $this->mobileUserInfo($group_id, $mobile, $face);
            return $this->getResponseFail(ErrCode::FACE_VERIFY_REPEAT_SIGN_IN_ERR, Lang::get('person.repeat_sign_in'), $result_data);
        }

        $update_data['status'] = 2;
        $update_data['sign_in_at'] = date('Y-m-d H:i:s');

        $r = $meetingUser->where('meeting_id', '=', $group_id)->where('mobile', '=', $mobile)->update($update_data);

        if (!$r) {
            throw ApiCommonException::faceVerifyErr();
        }

        Meeting::where('id', $group_id)->increment('sign_in_num', 1);

        $result_data = $this->mobileUserInfo($group_id, $mobile, $face);

        return $this->getResponseSuccess($result_data);
    }

    //获取图片签到用户信息
    private function imageUserInfo($group_id, $face_id, $face)
    {
        $user_info = MeetingUser::select('real_name', 'mobile', 'face_image', 'tag', 'sign_in_at')->where('meeting_id', '=', $group_id)->where('person_face_id', '=', $face_id)->first();

        $face_image_url = Oss::getPublicObjectURL($user_info->face_image);
        $user_info->face_image_url = $face_image_url;

        $detect_face = $face->detectFaceUrl($face_image_url);

        $face_info = null;
        if (isset($detect_face['face'][0])) {
            if (isset($detect_face['face'][0]['face_shape'])) {
                $face_info = by_key_reitem($detect_face['face'][0],'face_shape');
            }
        }

        if (!empty($face_info)) {
            if (!empty($face_info['beauty'])) {
                $user_update_data['beauty'] = $face_info['beauty'];

                MeetingUser::where('meeting_id', '=', $group_id)->where('person_face_id', '=', $face_id)->update($user_update_data);
            }
        }

        $result_data['user_info'] = $user_info;
        $result_data['face'] = $face_info;

        return $result_data;
    }

    //获取手机号用户信息
    private function mobileUserInfo($group_id, $mobile, $face)
    {
        $user_info = MeetingUser::select('real_name', 'mobile', 'face_image', 'tag', 'sign_in_at')->where('meeting_id', '=', $group_id)->where('mobile', '=', $mobile)->first();

        $face_image_url = Oss::getPublicObjectURL($user_info->face_image);
        $user_info->face_image_url = $face_image_url;

        $detect_face = $face->detectFaceUrl($face_image_url);

        $face_info = null;
        if (isset($detect_face['face'][0])) {
            if (isset($detect_face['face'][0]['face_shape'])) {
                $face_info = by_key_reitem($detect_face['face'][0],'face_shape');
            }
        }

        if (!empty($face_info)) {
            if (!empty($face_info['beauty'])) {
                $user_update_data['beauty'] = $face_info['beauty'];

                MeetingUser::where('meeting_id', '=', $group_id)->where('mobile', '=', $mobile)->update($user_update_data);
            }
        }

        $result_data['user_info'] = $user_info;
        $result_data['face'] = $face_info;

        return $result_data;
    }
}